package cn.vawn.exam.service.impl;

import cn.vawn.base.dto.PageDTO;
import cn.vawn.base.dto.RequestPageDTO;
import cn.vawn.base.util.DateUtil;
import cn.vawn.base.util.StringArrayUtil;
import cn.vawn.exam.entity.*;
import cn.vawn.exam.mapper.AnswerMapper;
import cn.vawn.exam.mapper.PaperMapper;
import cn.vawn.exam.mapper.PaperTypeMapper;
import cn.vawn.exam.mapper.QuestionSerialMapper;
import cn.vawn.exam.service.IAnswerService;
import cn.vawn.exam.service.IPaperService;
import cn.vawn.exam.service.IQuestionSerialService;
import cn.vawn.exam.service.IQuestionsService;
import cn.vawn.exam.service.exception.DataNotFoundException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("paperService")
public class PaperServiceImpl implements IPaperService {

	private static Logger logger = LoggerFactory.getLogger(Class.class);

	@Resource
	private PaperMapper paperMapper;

	@Resource
	private IQuestionsService questionService;

	@Resource
	private IAnswerService answerService;

	@Resource
	private AnswerMapper answerMapper;

	@Resource
	private IQuestionSerialService questionSerialService;

	@Resource
	private QuestionSerialMapper questionSerialMapper;

	@Resource
	private PaperTypeMapper paperTypeMapper;

	@Override
	public PageDTO getAllPaper(RequestPageDTO requestPageDTO) {
		PageDTO pd = new PageDTO();

		int pageNumber = requestPageDTO.getPageNumber();
		int pageSize = requestPageDTO.getPageSize();
		String sort = requestPageDTO.getSort();
		String desc = requestPageDTO.getDesc();
		if(pageNumber > 0 &&  pageSize > 0){
			PageHelper.startPage(pageNumber, pageSize);
		}
		if(!sort.isEmpty() && !desc.isEmpty()){
			PageHelper.orderBy(sort + " " + desc);
		}
		List<Paper> papers = paperMapper.selectAllPaper();
		pd.setPageNumber(pageNumber);
		pd.setPageSize(pageSize);
		pd.setTotal((int) new PageInfo(papers).getTotal());
		pd.setData(new PageInfo(papers).getList());

		return pd;
	}

	@Override
	public List<PaperType> getAllPaperType() {
		return paperTypeMapper.selectAllType();
	}

	@Override
	public PageDTO getPartPaper(RequestPageDTO requestPageDTO,String name, String type, String startTime, String endTime) {
		//
		Date startDate = DateUtil.parseDate(startTime, "yyyy-MM-dd");
		Date endDate = DateUtil.parseDate(endTime, "yyyy-MM-dd");

		PageDTO pd = new PageDTO();

		int pageNumber = requestPageDTO.getPageNumber();
		int pageSize = requestPageDTO.getPageSize();
		String sort = requestPageDTO.getSort();
		String desc = requestPageDTO.getDesc();
		if(pageNumber > 0 &&  pageSize > 0){
			PageHelper.startPage(pageNumber, pageSize);
		}
		if(!sort.isEmpty() && !desc.isEmpty()){
			PageHelper.orderBy(sort + " " + desc);
		}

		List<Paper> papers = paperMapper.selectPartPaper(name, type, startDate, endDate);

		pd.setPageNumber(pageNumber);
		pd.setPageSize(pageSize);
		pd.setTotal((int) new PageInfo(papers).getTotal());
		pd.setData(new PageInfo(papers).getList());

		return pd;
	}

	@Override
	public void deletePaper(int paperId) {
		//�ж������Ƿ����
		Paper paper = paperMapper.selectPaperById(paperId);

		if(paper == null) {
			throw new DataNotFoundException("数据不存在，请刷新后重试");
		}

		paperMapper.deleteById(paperId);

	}

	@Override
	public List<Map<String, Object>> getAllPapaerName() {
		return paperMapper.selectAllName();
	}

	@Override
	public List<Map<String, Object>> getPaperAllConetnt(int paperId) {
		//
		Paper paper = paperMapper.selectPaperById(paperId);

		//�ж������Ƿ����
		if(paper == null) {
			throw new DataNotFoundException("数据不存在，请刷新后重试");
		}

		List<Map<String, Object>> paperContent = new ArrayList<>();

		Map<String, Object> datas = new HashMap<>();
		datas.put("paperId", paperId);
		datas.put("name", paper.getName());
		datas.put("type", paper.getType());

		//��ȡ�ʾ������е�questions
		String questionsIds = paper.getQuestionsIds();

		String[] qIds = questionsIds.split(",");
		//���ַ�������ת�������ͼ���
		List<Integer> questionIds = StringArrayUtil.stringArrToList(qIds);

		List<Questions> questions = questionService.batchQuestions(questionIds);

		List<Map<String, Object>> questionsList = new ArrayList<>();
		for(Questions question : questions) {
			Map<String, Object> questionDatas = new HashMap<>();

			questionDatas.put("questionsId", question.getId());
			questionDatas.put("content", question.getContent());
			questionDatas.put("optionType", question.getOptionType());

			QuestionSerial qSerial = new QuestionSerial();
			qSerial.setPaperId(paperId);
			qSerial.setQuestionsId(question.getId());
			QuestionSerial questionSerial = questionSerialService.getQuestionSerial(qSerial);

			questionDatas.put("questionSerial", questionSerial.getSerial());

			//��ȡ��Ŀ�е�AnswerIds�����ַ�������ת�������ͼ���
			List<Integer> answerIds =
					StringArrayUtil.stringArrToList(
							question.getAnswerIds().split(","));

			List<Answer> answers = answerService.batchSelectAnswers(answerIds);

			List<Map<String, Object>> answerList = new ArrayList<>();
			for(Answer answer : answers) {
				Map<String, Object> answerDatas = new HashMap<>();

				answerDatas.put("answerId", answer.getId());
				answerDatas.put("content", answer.getContent());
				answerDatas.put("unUsedSerialNumIds", answer.getUnUsedSerialNumIds());
//				answerDatas.put("serial", answer.getSerial());
				answerDatas.put("localUnitermIds", answer.getLocalUnitermIds());

				answerList.add(answerDatas);
			}

			questionDatas.put("answers", answerList);

			questionsList.add(questionDatas);
		}

		datas.put("questions", questionsList);

		paperContent.add(datas);

		return paperContent;

	}

	@Override
	public void updatePaper(Paper paper, Integer userId) {
		Paper p = paperMapper.selectPaperById(paper.getId());

		logger.info(p + "");
		logger.info(paper.getId() + "");

		if(p == null) {
			throw new DataNotFoundException("数据不存在，请刷新后重试");
		}
		p.setId(paper.getId());
		p.setName(paper.getName());
		p.setType(paper.getType());
		p.setUpdatedBy(userId);
		p.setUpdatedTime(new Date());
		paperMapper.updateById(paper);
	}

	@Override
	public void addPaper(Paper paper) {
		paperMapper.insertPaper(paper);
	}

	@Override
	public Paper getPaperById(int paperId) {
		return paperMapper.selectPaperById(paperId);
	}

	@Override
	public void insertPaper(Paper paper, List<QuestionSerial> questionSerials) {
		paperMapper.insertPaper(paper);
		int paperId = paper.getId();
		System.out.println("**********  paperId = " + paperId + "*********");

		for (QuestionSerial serial : questionSerials) {
			serial.setPaperId(paperId);
			questionSerialMapper.insertQuestionSerial(serial);
		}
	}

	@Override
	public void updatePaper(Paper paper, List<QuestionSerial> questionSerials) {
		paperMapper.updatePaper(paper);
		for (QuestionSerial serial : questionSerials) {
			questionSerialMapper.dlt(serial.getPaperId());
		}
		for (QuestionSerial serial : questionSerials) {
			questionSerialMapper.insert(serial);
		}
	}

	@Override
	public void updateAnswer(List<String> serials) {
		for(int i = 0; i < serials.size(); i++) {
			String answerSerial = serials.get(i);
			String[] answer = answerSerial.split(",");
			if(answer.length > 1) {
				answerMapper.updateSerial(Integer.parseInt(answer[0]),answer[1]);
			}
		}
	}

}
